package com.itachi.common.sensitive.config;


import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.itachi.common.sensitive.annotation.Sensitive;
import com.itachi.common.sensitive.enums.DesensitizedType;

import java.io.IOException;
import java.util.Objects;

/**
 * 数据脱敏序列化过滤
 */
public class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {


    private DesensitizedType desensitizedType;


    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (desensitization()){
            jsonGenerator.writeString(desensitizedType.desensitizer().apply(s));
        }else{
            jsonGenerator.writeString(s);
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        Sensitive annotation = beanProperty.getAnnotation(Sensitive.class);
        if (Objects.nonNull(annotation) && Objects.equals(String.class,beanProperty.getType().getRawClass())){
            desensitizedType = annotation.desensitizedType();
            return this;
        }
        return serializerProvider.findValueSerializer(beanProperty.getType(),beanProperty);
    }

    /**
     * 判断脱敏
     * @return
     */
    private boolean desensitization()
    {
        return true;
    }

}
